package com.cpit.qualitycontrol.service.impl;

import com.cpit.platform.common.constant.SystemConstant;
import com.cpit.platform.common.entity.TableDataQueryCondition;
import com.cpit.platform.common.entity.TableJsonData;
import com.cpit.platform.common.utils.BeanUtil;
import com.cpit.platform.common.utils.Encodes;
import com.cpit.platform.common.utils.FileUtil;
import com.cpit.platform.config.UploadPathConfig;
import com.cpit.platform.log.LogOperator;
import com.cpit.qualitycontrol.dao.ProcessRuleRepository;
import com.cpit.qualitycontrol.dao.WorkOrderTypeRepository;
import com.cpit.qualitycontrol.entity.WorkOrderType;
import com.cpit.qualitycontrol.service.WorkOrderTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.List;

/**
 * Created by Hull on 2017/9/28.
 * @author Hull
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class WorkOrderTypeServiceImpl implements WorkOrderTypeService {
    private final String loggerName = this.getClass().getName();

    private final String imageFilePath = "/System/WorkOrderType";

    @Autowired
    private WorkOrderTypeRepository rep = null;

    @Autowired
    private ProcessRuleRepository processRuleRepository = null;

    @Autowired
    private UploadPathConfig uploadPathConfig;

    @Override
    public WorkOrderType findById(Long id) {
        return this.rep.findOne(id);
    }

    @Override
    public List<WorkOrderType> findAll() {
        return this.rep.findAll();
    }

    @Override
    public List<WorkOrderType> findByCondition(int page, int size, String order, String orderBy, String pattern) {
        if(orderBy == null || orderBy.length() == 0) {
            orderBy = "id";
        }
        Sort.Direction der = order.equals(SystemConstant.DIRECTION_ASC) ? Sort.Direction.ASC : Sort.Direction.DESC;
        PageRequest request = new PageRequest(page - 1, size, new Sort(der, orderBy));
        Page<WorkOrderType> pg;
        if(pattern == null || "".equals(pattern)) {
            pg = this.rep.findAll(request);
        } else {
            pg = this.rep.findByNameContaining(pattern, request);
        }
        return pg.getContent();
    }

    @Override
    public WorkOrderType create(WorkOrderType workOrderType) throws Exception {
        if(workOrderType == null) {
            throw new Exception("参数为空");
        }
        if(workOrderType.getId() != null && workOrderType.getId()>0) {
            LogOperator.info(loggerName, "工单类型ID已赋值");
            workOrderType.setId(0L);
        }
        this.checkUniqueConstraint(workOrderType);
        this.handleIconFile(workOrderType);

        return this.rep.save(workOrderType);
    }

    @Override
    public WorkOrderType modify(WorkOrderType workOrderType) throws Exception {
        if(workOrderType == null) {
            throw new Exception("参数为空");
        }
        WorkOrderType workOrderType1 = rep.findOne(workOrderType.getId());
        if(workOrderType1 == null) {
            LogOperator.info(loggerName, "修改的工单类型不存在:" + workOrderType);
            throw new Exception("修改的工单类型不存在");
        }
        this.checkUniqueConstraint(workOrderType);

        //如果图标发生了变化删除原有图标文件
        if (!workOrderType.getIconFile().equals(workOrderType1.getIconFile())) {
            this.deleteIconFile(workOrderType1);
        }
        this.handleIconFile(workOrderType);

        return this.rep.save(workOrderType);
    }

    @Override
    public void delete(WorkOrderType workOrderType) throws Exception {
        if(workOrderType == null) {
            throw new Exception("参数为空");
        }
        this.delete(workOrderType.getId());
    }

    @Override
    public void delete(Long id) throws Exception {
        WorkOrderType workOrderType = this.rep.findOne(id);
        if(workOrderType == null) {
            LogOperator.info(loggerName, "删除的工单类型不存在:id=" + id);
            throw new Exception("删除的工单类型不存在");
        }

        if (this.processRuleRepository.countProcessRulesByWorkOrderTypeId(id) > 0) {
            LogOperator.info(loggerName, "存在关联的流程规则，不能删除工单类型:" + id);
            throw new Exception("存在关联的流程规则，不能删除工单类型");
        }

        //删除原有图标文件
        this.deleteIconFile(workOrderType);
        this.rep.delete(id);
    }

    @Override
    public TableJsonData findByConditionJqg(TableDataQueryCondition cond) {
        PageRequest request = ServiceUtils.getPageRequestByTableDataQueryCondition(cond);

        String pattern = BeanUtil.getStringIdentifyNull(cond.getQueryCond().get("pattern"));
        Page<WorkOrderType> ret;
        if(pattern == null || "".equals(pattern)) {
            ret = this.rep.findAll(request);
        } else {
            ret = this.rep.findByNameContaining(pattern, request);
        }
        return new TableJsonData(cond, ret.getTotalElements(), ret.getContent());
    }

    @Override
    public WorkOrderType findByName(String name) {
        return rep.findByName(name);
    }

    private void checkUniqueConstraint(WorkOrderType workOrderType) throws Exception {
        WorkOrderType workOrderType1 = rep.findByName(workOrderType.getName());
        if(workOrderType1 != null && !workOrderType1.getId().equals(workOrderType.getId())) {
            LogOperator.info(loggerName, "同名工单类型已存在:" + workOrderType.getName());
            throw new Exception("同名工单类型已存在");
        }
    }

    /**
     * 在删除或修改时，根据原记录中Base64编码的文件名删除对应的图标文件
     * @param workOrderType
     */
    private void deleteIconFile(WorkOrderType workOrderType) {
        String fileName = Encodes.decodeBase64String(workOrderType.getIconFile());
        (new File(uploadPathConfig.getPath() + imageFilePath, fileName.substring(fileName.lastIndexOf("/") + 1))).delete();
    }

    /**
     * 处理图标文件，如果在临时目录中，则从临时目录移到正式目录并修改URL字段值，否则不做任何操作
     * @param workOrderType 工单类型Bean
     * @throws Exception 移动文件失败跑出异常
     */
    private void handleIconFile(WorkOrderType workOrderType) throws Exception {
        String oldUrl = workOrderType.getIconFile();
        if (oldUrl.contains(uploadPathConfig.getTemp().replace(uploadPathConfig.getPath(), ""))) {
            String fileName = oldUrl.substring(oldUrl.lastIndexOf("/") + 1, oldUrl.length());
            FileUtil.moveFile(uploadPathConfig.getTemp(), fileName, uploadPathConfig.getPath() + imageFilePath, fileName);
            workOrderType.setIconFile(uploadPathConfig.getWebDownloadBase64Path(uploadPathConfig.getPath() + imageFilePath + "/" + fileName));
        }
    }
}
